package com.linkgie.galaxyframework.utils;

public abstract class ListPagination implements Pagination {

	private long pageIndex = 0;

	private Long pageSize;

	private Long totalSize;

	public ListPagination() {
	}

	public ListPagination(long pageIndex, long pageSize) {
		this.setPagination(pageIndex, pageSize, null);
	}

	public ListPagination(long pageIndex, long pageSize, Long totalSize) {
		this.setPagination(pageIndex, pageSize, totalSize);
	}

	public ListPagination(Pagination pagination) {
		if (pagination != null) {
			this.setPagination(pagination.getPageIndex(), pagination.getPageSize(), pagination.getTotalSize());
		} else {
			this.pageIndex = 0;
			this.pageSize = null;
			this.totalSize = null;
		}
	}

	/**
	 * 设置分页信息；
	 * 
	 * @param pageIndex 当前页索引；
	 * @param pageSize  页大小；
	 * @param totalSize 总记录数；
	 *                  <p>
	 *                  如果设置为负数，表示不知道总记录数，最终总记录数被设置为
	 *                  {@link Pagination#UNKNOWN_SIZE}；
	 */
	public void setPagination(long pageIndex, long pageSize, Long totalSize) {
		// 检查分页参数；
		CollectionUtils.checkListPagination(listSize(), pageIndex, pageSize, totalSize);

		if (totalSize != null && totalSize.longValue() < 0) {
			this.totalSize = Pagination.UNKNOWN_SIZE;
		} else {
			this.totalSize = totalSize;
		}
		this.pageIndex = pageIndex;
		this.pageSize = pageSize;
	}

	abstract int listSize();

	@Override
	public long getTotalSize() {
		return totalSize == null ? listSize() : totalSize;
	}

	@Override
	public long getPageIndex() {
		return pageIndex;
	}

	@Override
	public long getPageSize() {
		if (pageSize == null) {
			int listSize = listSize();
			// 页大小至少为 1 ；
			return listSize < MIN_PAGE_SIZE ? MIN_PAGE_SIZE : listSize;
		}
		return pageSize.longValue();
	}

}
